package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.config.ConsulConfig;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.contract.VendoutContract;
import com.lkd.contract.VendoutData;
import com.lkd.dao.OrderDao;
import com.lkd.feign.UserService;
import com.lkd.vo.*;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.service.OrderService;
import com.lkd.utils.DistributedLock;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public OrderEntity getByOrderNo(String orderNo) {
        QueryWrapper<OrderEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(OrderEntity::getOrderNo, orderNo);
        return this.getOne(qw);
    }

    /**
     * 创建小程序支付订单
     *
     * @param payVO
     * @return
     */
    @Override
    public OrderEntity createOrder(PayVO payVO) {
        //查询售货机该商品是否存在
        if (!vmService.hasCapacity(payVO.getInnerCode(), Long.valueOf(payVO.getSkuId()))) {
            throw new LogicException("该商品已经售空");
        }
        //创建小程序订单实体
        var orderEntity = new OrderEntity();

        //openId
        orderEntity.setOpenId(payVO.getOpenId());
        orderEntity.setOrderNo(payVO.getInnerCode() + System.nanoTime());   //订单编号
        orderEntity.setPayStatus(VMSystem.PAY_STATUS_NOPAY);       //设置未支付

        //根据售货机编号查询出售货机的信息,复制给订单对象
        var vmInfo = vmService.getVMInfo(payVO.getInnerCode());
        BeanUtils.copyProperties(vmInfo, orderEntity);
        orderEntity.setAddr(vmInfo.getNodeAddr());

        //根据商品编号查询商品信息,复制给订单对象

        SkuVO sku = vmService.getSku(payVO.getSkuId());
        BeanUtils.copyProperties(sku, orderEntity);

        //给订单的真实价格信息设置进去
        orderEntity.setAmount(sku.getRealPrice());

        //设置订单状态
        orderEntity.setStatus(VMSystem.ORDER_STATUS_CREATE);

        //计算合作分账金额

        //根据合作商id获取合作商信息
        PartnerVO partner = userService.getPartner(vmInfo.getOwnerId());
        //计算分账金额
        BigDecimal bd = new BigDecimal(sku.getRealPrice());
        int bill = bd.multiply(new BigDecimal(partner.getRatio())).divide(new BigDecimal(100), 0, RoundingMode.HALF_UP).intValue();
        //将计算好的分账金额设置到订单对象中
        orderEntity.setBill(bill);
        //调用业务方法创建小程序订单
        this.save(orderEntity);


        //将订单放到延迟队列中,10分钟后检查支付状态!!!!!!!!!!!!!!!!!!!!!!!
        var orderCheck = new OrderCheck();
        orderCheck.setOrderNo(orderEntity.getOrderNo());
        try {
            mqttProducer.send("$delayed/600/" + TopicConfig.ORDER_CHECK_TOPIC, 2, orderCheck);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("send to emq error", e);
        }


        //返回订单实体
        return orderEntity;
    }

    /**
     * 发送出货通知
     *
     * @param orderNo
     * @param skuId
     * @param innerCode
     * @return
     */
    @Override
    public boolean vendOut(String orderNo, Long skuId, String innerCode) {
        //封装协议中的数据
        var reqData = new VendoutData();
        reqData.setOrderNo(orderNo);
        reqData.setSkuId(skuId);
        //封装协议
        var contract = new VendoutContract();
        contract.setInnerCode(innerCode);
        contract.setVendoutData(reqData);
        //向emq发送消息  向售货机微服务发送出货请求
        try {
            mqttProducer.send(TopicConfig.VMS_VENDOUT_TOPIC, 2, contract);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.info("send vendout error.", e);
            return false;
        }
        return true;
    }

}
